#include "stdafx.h"
#include "Clique.h"

const char* INPUTGRAPH = "Inputgraph.dot";
const char* COMPLGRAPH = "complgraph.dot";
const char* RESGRAPH   = "resultgraph.dot";
const int ERROR = -1;

//return complementary graph to given graph
void complementary(const Graph& g, Graph& target)
{
	VIter vi, vi_end;

	tie(vi, vi_end) = vertices(g); 
	for(VIter i = vi; i != vi_end; i++)
	{
		AdjItr ai, aend;
		//set of adjacent vertices to i'th vertex
		Indset adj;
		detail::neighbors(g, *i, inserter(adj, adj.begin()));
		for(VIter j = i; j != vi_end; j++)
		{
			//if j'th vertex isnt adjacent to i'th
			if(j != i && adj.find(*j) == adj.end())
			{
				add_edge(*i, *j, target);
			}			
		}
	}
}

void writeGrToFile(Graph& g, const char* name)
{
	ofstream file(name);		 
	property_map<Graph, vertex_name_t>::type nameM = get(vertex_name, g);
	write_graphviz(file, g, make_label_writer(nameM));
	//write_graphviz(cout, g);
	file.close();
}

int graph_read(Graph& g) 
{
	dynamic_properties dp;	
	string input;

	cin >> input;
	ifstream file(input.c_str());
	if(!file)
	{
		cerr << "Error: cannot open the file. \n";
		file.close();
		return ERROR;
	}
	property_map<Graph, vertex_name_t>::type nameM =
		get(vertex_name, g);
	dp.property("name", nameM);
	read_graphviz(file, g, dp, "name");
	file.close();
	return 0;
}

int main(int,char*[])
{
	clock_t start, end;
	Graph testGraph,complGraph;
	
	cout << "Enter dot file name with graph: \n";
	if(graph_read(testGraph) == ERROR) 
		return ERROR;
	//write given graph to the dot file
	writeGrToFile(testGraph, INPUTGRAPH);
	complementary(testGraph, complGraph);
	cout << "Complementary graph is calculated.";
	//write complementary graph to the dot file
	writeGrToFile(complGraph, COMPLGRAPH);
	start = clock();
	Clique allCliques = Clique(complGraph);
	cout << "\n Searching Max clique in complementary graph... \n";
	//label vertex from max independent set of graph
	allCliques.findIndependentSet(testGraph);
	end = clock();
	writeGrToFile(testGraph, RESGRAPH);	
	printf ("Running time is %2.2f seconds.\n", (double)(end - start) / CLOCKS_PER_SEC);
}
